import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Input, message, TreeSelect } from 'antd';
import { connect } from 'react-redux';
import storage from '../../../utils/storage';
import services from '../../../services/api';
const { TreeNode } = TreeSelect;

@connect(mapStateToProps)
class ProjectAdd extends Component {
  constructor(props) {
    super(props);
    this.form = null;
    this.api = 'project';
  }

  handleSubmit = () => {
    const { actionType, closeModal, record = {} } = this.props;
    this.form.validateFields((err, values) => {
      if (!err) {
        const { name, code, orgCodes } = values;
        const params = {
          name,
          code,
          orgCodes: orgCodes.map((item) => item.value),
          id: record.id,
        };
        services[this.api][actionType](params).then((data) => {
          if (data.code === '0') {
            message.success(data.msg);
            closeModal && closeModal();
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  getOrgTitleByCode(orgCodeList) {
    return orgCodeList.map((value) => ({ label: '', value }));
  }

  renderTree = (data) => {
    return data.map((item) => {
      if (item.children && item.children.length) {
        return (
          <TreeNode value={item.code} title={item.name} key={item.id}>
            {this.renderTree(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode value={item.code} title={item.name} key={item.id} />;
    });
  };

  onSelectOrgsChange(value) {
    if (value.length <= 1) {
      return value;
    }
    const index = value.findIndex((item) => item.value === '-1');
    if (index > 0) {
      return [{ label: '', value: '-1' }];
    } else if (index === 0) {
      return value.slice(1, value.length);
    } else {
      return value;
    }
  }

  render() {
    const { actionType, record = {}, orgList, value = {} } = this.props;
    const { name, code } = record;
    const { visibleOrgCodes = [] } = value;
    const newOrgList = [{ code: '-1', name: '所有机构', id: '-1' }].concat(orgList);
    const formItems = [
      {
        label: {
          label: '项目名称',
          className: 'tantuer-form-item2',
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [{ required: true, message: '请输入项目名称' }],
        },
        component: <Input placeholder='请输入' disabled={actionType === 'detail'} />,
      },
      {
        label: {
          label: '项目code',
          className: 'tantuer-form-item2',
        },
        name: 'code',
        options: {
          initialValue: code,
          rules: [
            { required: true, message: '请填写项目Code' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
          ],
        },
        component: <Input placeholder='请输入' disabled={actionType === 'detail' || actionType === 'update'} />,
      },
      {
        label: {
          label: '可见机构',
          className: 'tantuer-form-item2',
        },
        name: 'orgCodes',
        options: {
          initialValue: this.getOrgTitleByCode(visibleOrgCodes),
          rules: [{ required: true, message: '请选择可见机构' }],
          getValueFromEvent: this.onSelectOrgsChange,
        },
        component: (
          <TreeSelect treeCheckable treeCheckStrictly>
            {this.renderTree(newOrgList)}
          </TreeSelect>
        ),
      },
    ].filter(Boolean);

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        createForm={(ref) => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
        hideSubmit={this.actionType === 'detail'}
        modelId={null}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    orgList: state.global.orgList,
  };
}

export default ProjectAdd;
